<?php

	include_once('base.php');

	// from php manual page
	function formatBytes($val, $digits = 3, $mode = 'SI', $bB = 'B'){ //$mode == 'SI'|'IEC', $bB == 'b'|'B'
		$si = array('', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y');
		$iec = array('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi');
		switch(strtoupper($mode)) {
			case 'SI' : $factor = 1000; $symbols = $si; break;
			case 'IEC' : $factor = 1024; $symbols = $iec; break;
			default : $factor = 1000; $symbols = $si; break;
		}
		switch($bB) {
			case 'b' : $val *= 8; break;
			default : $bB = 'B'; break;
		}
		for($i=0;$i<count($symbols)-1 && $val>=$factor;$i++)
			$val /= $factor;
		$p = strpos($val, '.');
		if($p !== false && $p > $digits) $val = round($val);
		elseif($p !== false) $val = round($val, $digits-$p);
		return round($val, $digits) . ' ' . $symbols[$i] . $bB;
	}

    if(array_key_exists('nodes', $_GET)){
        $nodes = json_decode($_GET['nodes']);
    } else {
	    $nodes = array(isset($_GET['node']) ? $_GET['node'] : '');
    }
    $node = $nodes[0];

	if(strcasecmp($node, 'www') ==0 ){
		$node = '';
	}

	if(strpos($node, '..') !== false){
		die('Nice try buddy.');
	}

    function getNodes($node, $nodes){
        $outNodes = array();
        $directory = BASE_DIR.'/'.$node;
        if (is_dir($directory)){
            $d = dir($directory);
            while($f = $d->read()){
                if($f == '.' || $f == '..'/* || substr($f, 0, 1) == '.'*/) continue;

                $filename = $directory . '/' . $f;
                date_default_timezone_set('America/Los_Angeles');

                if(is_dir($directory.'/'.$f)){
                    $outNodes[] = array(
                        'text' => $f,
                        'id'   => ($node ? $node.'/' : '' ).$f,
                        'cls'  => 'folder'
                    );
                    if(in_array(($node ? $node.'/' : '' ).$f, $nodes)){
                        $outNodes[count($outNodes)-1]['expanded'] = true;
                        $outNodes[count($outNodes)-1]['children'] = getNodes($node.'/'.$f, $nodes);
                    }
                } else {
                    $size = formatBytes(filesize($filename), 2);
                    $outNodes[] = array(
                        'text' => $f,
                        'id'   => ($node ? $node.'/' : '' ).$f,
                        'leaf' => true,
                        'cls'  => 'file'
                    );
                }
            }
            $d->close();
        }
        return $outNodes;
    }

	echo json_encode(getNodes($node, $nodes));